package com.roadmap.struts.action.admin.life;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.roadmap.biz.common.IManager;
import com.roadmap.biz.common.ManagerFactory;
import com.roadmap.common.BaseEntity;
import com.roadmap.common.RdcConst;
import com.roadmap.entities.ext.ExecutionExt;
import com.roadmap.entities.ext.TaskExt;
import com.roadmap.exception.ActionNotSupportedException;
import com.roadmap.exception.EntityNotFoundException;
import com.roadmap.exception.InvalidQueryException;
import com.roadmap.exception.InvalidValueException;
import com.roadmap.exception.NotAuthorizedException;
import com.roadmap.exception.NotMatchedException;
import com.roadmap.exception.NullObjectException;
import com.roadmap.exception.ServerException;
import com.roadmap.struts.action.ActionConst;
import com.roadmap.struts.action.RdcDispatchAction;

public class ExecAction extends RdcDispatchAction {

	@Override
	public boolean isFormSubmitted(HttpServletRequest request) throws Exception {
		return false;
	}

	@Override
	public ActionForward doAll(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String ownerId = request
				.getParameter(ActionConst.Aspirant_Id_In_Request);
		if (ownerId == null || ownerId.trim().length() == 0) {
			return handleInvalidUser(request, "/exec.do");
		}
		String currUserId = getUIDFromSession(request);
		String taskId = request.getParameter(ActionConst.Parent_Id_In_Request);
		int currentPage = getCurrentPageNum(request);

		List list = null;
		IManager execMgr = ManagerFactory.getInstance(RdcConst.EXEC,
				currUserId, ownerId);
		execMgr.setPage(currentPage);

		if (taskId != null) {
			// 优先根据给定的任务ID来查执行记录
			list = execMgr.getEntitiesOfParent(taskId);
		}
		else {
			// 根据某执行记录ID来查任务所有的执行记录
			String execId = request
					.getParameter(ActionConst.Item_Id_In_Request);
			ExecutionExt exec = (ExecutionExt) execMgr.getEntityExt(execId);
			if (exec == null) {
				throw new EntityNotFoundException();
			}
			list = exec.getBrothers();

			taskId = exec.getTaskId();
		}

		if (list != null && !list.isEmpty()) {
			request.setAttribute("execs", list);
			createPagingInfoInRequest(request, execMgr);
		}

		retrieveTask(request, currUserId, ownerId, taskId);

		// 如果用户不是访问项拥有者，则从request里移除拥有者标识
		if (!currUserId.equals(ownerId)) {
			request.removeAttribute(ActionConst.Visitor_Is_Owner);
		}
		return mapping.findForward("getexecs");
	}

	private void retrieveTask(HttpServletRequest request, String currUserId,
			String ownerId, String taskId) throws NullObjectException,
			InvalidQueryException, ServerException, InvalidValueException,
			EntityNotFoundException, NotMatchedException,
			NotAuthorizedException, ActionNotSupportedException {
		if (taskId == null) {
			throw new NullObjectException("Task id is null.");
		}

		IManager taskMgr = ManagerFactory.getInstance(RdcConst.TASK,
				currUserId, ownerId);
		TaskExt task = (TaskExt) taskMgr.getEntityExt(taskId);
		if (task == null) {
			throw new EntityNotFoundException();
		}

		task.setAspirantId(null);
		task.setCreatedTime(null);
		task.setGoalId(null);
		task.setRealEndDate(null);
		task.setRealStartDate(null);
		task.setScheduledEndDate(null);
		task.setUpdatedTime(null);
		request.setAttribute("task", task);
	}

	@Override
	protected ActionForward doView(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String ownerId = request
				.getParameter(ActionConst.Aspirant_Id_In_Request);
		if (ownerId == null || ownerId.trim().length() == 0) {
			return handleInvalidUser(request, "/exec.do?act=view");
		}

		String curUserId = getUIDFromSession(request);
		String itemId = request.getParameter(ActionConst.Item_Id_In_Request);
		IManager parentMgr = ManagerFactory.getInstance(RdcConst.EXEC, curUserId,
				ownerId);
		BaseEntity exec = parentMgr.get(itemId);
		if (exec == null) {
			throw new EntityNotFoundException(String.format(
					"Parent entity %s was not found.", itemId));
		}

		request.setAttribute("parentEntry", exec);

		int currentPage = getCurrentPageNum(request);
		IManager cmMgr = ManagerFactory.getInstance(RdcConst.COMMENT,
				curUserId, ownerId, RdcConst.EXEC);
		cmMgr.setPage(currentPage);

		List comments = cmMgr.getEntitiesOfParent(itemId);
		if (comments != null && !comments.isEmpty()) {
			request.setAttribute("comments", comments);
			createPagingInfoInRequest(request, cmMgr);
		}
		return mapping.findForward("getcomments");
	}

}